package com.yhxd.modular.news.service;

import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.yhxd.modular.institutions.entity.Dept;
import com.yhxd.modular.institutions.entity.QDept;
import com.yhxd.modular.news.dao.AllInfoDao;
import com.yhxd.modular.news.entity.Classify;
import com.yhxd.modular.news.entity.News;
import com.yhxd.modular.news.entity.QNews;
import com.yhxd.utils.DateUtils;
import com.yhxd.utils.QueryDslUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AllInformationService {

    @Autowired
    private JPAQueryFactory factory;

    @Autowired
    private AllInfoDao allInfoDao;

    /**
     * 分页查询文章列表
     *
     * @param pageRequest
     * @return
     */
    public Page<News> findAll(QPageRequest pageRequest, News dto) {
        QNews qNews = QNews.news;
        QDept qDept = QDept.dept;
        Predicate where = qNews.id.isNotNull();
        //信息标题
        if (ObjectUtils.isNotEmpty(dto.getTitle())) {
            where = ExpressionUtils.and(where, qNews.title.like("%" + dto.getTitle() + "%"));
        }
        //信息大类
        Classify parentClassify = dto.getParentClassify();
        if (ObjectUtils.isNotEmpty(parentClassify) && ObjectUtils.isNotEmpty(parentClassify.getId())) {
            where = ExpressionUtils.and(where, qNews.pcid.eq(dto.getParentClassify().getId()));
        }
        //信息小类
        Classify childClassify = dto.getChildClassify();
        if (ObjectUtils.isNotEmpty(childClassify) && ObjectUtils.isNotEmpty(childClassify.getId())) {
            where = ExpressionUtils.and(where, qNews.ccid.eq(dto.getChildClassify().getId()));
        }
        //信息类型
        if (ObjectUtils.isNotEmpty(dto.getConType())) {
            where = ExpressionUtils.and(where, qNews.conType.eq(dto.getConType()));
        }
        //信息状态
        if (ObjectUtils.isNotEmpty(dto.getStatus())) {
            where = ExpressionUtils.and(where, qNews.status.eq(dto.getStatus()));
        }
        //发布时间
        if (ObjectUtils.isNotEmpty(dto.getPublishDate())) {
            where = ExpressionUtils.and(where, qNews.publishDate.between(DateUtils.getTimesStart(dto.getPublishDate()), DateUtils.getTimesEnd(dto.getPublishDate())));
        }
        //有效期开始
        if (ObjectUtils.isNotEmpty(dto.getBeginDate())) {
            where = ExpressionUtils.and(where, qNews.beginDate.isNull().or(qNews.beginDate.loe(DateUtils.getTimesStart(dto.getBeginDate()))));
        }
        //有效期结束
        if (ObjectUtils.isNotEmpty(dto.getEndDate())) {
            where = ExpressionUtils.and(where, qNews.endDate.isNull().or(qNews.endDate.goe(DateUtils.getTimesStart(dto.getEndDate()))));
        }
        //部门
        Dept dept = dto.getDept();
        if (ObjectUtils.isNotEmpty(dept) && ObjectUtils.isNotEmpty(dept.getDepName())) {
            where = ExpressionUtils.and(where, qDept.depName.like("%" + dept.getDepName() + "%"));
        }
        //发布人
        if (ObjectUtils.isNotEmpty(dto.getPublishName())) {
            where = ExpressionUtils.and(where, qNews.publishName.like("%" + dto.getPublishName() + "%"));
        }
        QueryResults<News> newsList = this.factory
                .selectFrom(qNews)
                .leftJoin(qDept)
                .on(qNews.deptId.eq(qDept.id))
                .where(where)
                .orderBy(QueryDslUtils.getOrderSpecifier(pageRequest.getSort()))
                .offset(pageRequest.getOffset())
                .limit(pageRequest.getPageSize())
                .fetchResults();
        Page<News> newsPage = new PageImpl<>(newsList.getResults(), pageRequest, newsList.getTotal());
        return newsPage;
    }

    /**
     * 分页查询权限列表
     *
     * @param pageRequest
     * @return
     */
    public Page<News> findAll(PageRequest pageRequest, Long id) {
        Page<News> newList = this.allInfoDao.findByCcidAndStatusAndPublishDateIsNotNull(id , 1, pageRequest);
        return newList;
    }

    /**
     * 分页查询文章列表(用于前端页面展示)
     *
     * @param pageRequest
     * @return
     * @auther lzl
     */
    public Page<News> findPageNews(QPageRequest pageRequest, News dto) {
        QNews qNews = QNews.news;
        Predicate where = qNews.id.isNotNull();
        if (ObjectUtils.isNotEmpty(dto.getConType())) {      //信息类型
            where = ExpressionUtils.and(where, qNews.conType.eq(dto.getConType()));
        }
        if (ObjectUtils.isNotEmpty(dto.getParentClassify()) && ObjectUtils.isNotEmpty(dto.getParentClassify().getId())) {      //信息dalei
            where = ExpressionUtils.and(where, qNews.pcid.eq(dto.getParentClassify().getId()));
        } else {
            //最新动态只展示：部门简报,部门简报,工作简报,深圳不动产,通知公告5l,7l,9l,11l,13l
            List<Long> list = new ArrayList<>();
            for (Long i = 5l; i <= 13l; i = i + 2) {
                System.out.println(i);
                list.add(i);
            }
            where = ExpressionUtils.and(where, qNews.pcid.in(list));
        }
        if (ObjectUtils.isNotEmpty(dto.getChildClassify()) && ObjectUtils.isNotEmpty(dto.getChildClassify().getId())) {      //信息小类
            where = ExpressionUtils.and(where, qNews.ccid.eq(dto.getChildClassify().getId()));
        }
        where = ExpressionUtils.and(where, qNews.publishDate.isNotNull());
        where = ExpressionUtils.and(where, qNews.status.eq(1));

        QueryResults<News> newsList = this.factory
                .selectFrom(qNews)
                .where(where)
                .orderBy(QueryDslUtils.getOrderSpecifier(pageRequest.getSort()))
                .offset(pageRequest.getOffset())
                .limit(pageRequest.getPageSize())
                .fetchResults();
        Page<News> newsPage = new PageImpl<>(newsList.getResults(), pageRequest, newsList.getTotal());
        return newsPage;
    }

    /**
     * 按id删除数据
     *
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        QNews qNews = QNews.news;
        this.factory
                .delete(qNews)
                .where(qNews.id.eq(id))
                .execute();
    }

    //详情查询
    public News findById(Long id) {
        return this.allInfoDao.findById(id).orElse(null);
    }
}
